/***************************************************************************
*  Dispatcher.cpp
*
*  July 2007
*  Copyright  2007  RuijinZheng,China
*  Email mebetop@126.com
****************************************************************************/

/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */
#include "Dispatcher.hpp"
#include <fstream>
////////////////
/// ------>  public funtions
Dispatcher::Dispatcher()
{

      pthread_mutex_init(&mut,NULL);
      try{
          loadenvironment();
          initlibc();
          int proxycount=loadservers();
          if(proxycount==0){
                throw string("No available proxy server specified");
            }
      }
      catch(const string &s){
          Lowlayer::Errordeliver(s,strerror(errno));
          exit(0);
      }
      normal=NULL;
      detail=NULL;
      chain=NULL;
      udp=NULL;
}

Dispatcher::~Dispatcher(){
      dlclose(plibc);
}

bool Dispatcher::Setsockblock(const int &sock,int &flags){

      if(flags & O_NONBLOCK){
          if(fcntl(sock,F_SETFL, flags-O_NONBLOCK)==-1)
              return false;
      }
      return true;
}
bool Dispatcher::Suitablesocket(int  sockfd,  const  struct sockaddr *serv_addr){  
      int optval = 0,  tmp, flags;
      socklen_t optlen = sizeof(optval);
      if(((((struct sockaddr_in *)serv_addr)->sin_family == AF_INET6)||       \
                          (((struct sockaddr_in *)serv_addr)->sin_family == AF_INET))&&(((struct sockaddr_in *)serv_addr)->sin_addr.s_addr != 16777343)){
          if(getsockopt(sockfd, SOL_SOCKET, SO_TYPE, &optval, &optlen) != -1){
              if((optval == SOCK_STREAM)) {
                  return true;
              }
          }
      }
      return false;
}
bool Dispatcher::Restoresock(const int &sock,const int &flags){
      if(flags & O_NONBLOCK){
          if(fcntl(sock,F_SETFL, flags))
             return false;
      }
      return true;
}
Lowlayer * Dispatcher::Createlayer()
{
    if(strcmp(sfleatype.c_str(),"Normal")==0)
    {
         pthread_mutex_lock(&mut);
         if(normal==NULL)
              normal = Normalflealayer::Getonlyinstance(&oldconnect,&oldrecv,&oldsend,
                            &oldrecvfrom,&oldsendto);
         pthread_mutex_unlock(&mut);

         return normal;
    }
    else if(strcmp(sfleatype.c_str(),"Detailing")==0)
    {
         pthread_mutex_lock(&mut);
         if(detail==NULL)
              detail = Detailingflealayer::Getonlyinstance(&oldconnect,&oldrecv,&oldsend,
                            &oldrecvfrom,&oldsendto);

         pthread_mutex_unlock(&mut);

         return detail;

    }
    else if(strcmp(sfleatype.c_str(),"Chain")==0)
    {
         pthread_mutex_lock(&mut);
         if(chain==NULL)
              chain = Chainflealayer::Getonlyinstance(&oldconnect,&oldrecv,&oldsend,
                           &oldrecvfrom,&oldsendto);
         pthread_mutex_unlock(&mut);

         return chain;
    }else{
    	  Lowlayer::Errordeliver("Bad type to run  ","This program will exiting");
    	  exit(-1);
    }
}

Udpflealayer * Dispatcher::Createudplayer(){
    pthread_mutex_lock(&mut);
     if(udp==NULL){
         Udpflealayer *newudpflea = Udpflealayer::Getonlyinstance(&oldbind,&oldconnect,&oldrecv,
             &oldsend,&oldrecvfrom,&oldsendto);
             udp=newudpflea;                 
    }
    pthread_mutex_unlock(&mut);
 	return udp;
}

/// <------  public funtions
////////////////////////////////////


///////////////////////////////////
/// ------>  protected funtions
int Dispatcher::loadservers(){
	 fstream file;
	 string filepath=string(getenv("HOME"))+"/.netflea/proxyserver.list";
	 file.open(filepath.c_str(),ios::in);
	 char buf[1024];
	 char subsep[]=",:;";
	 char *subtoken=0;
	 int i=0;
	 while(file.getline(buf,1024)){
  		  Proxyserver tmp;
         tmp.sType=strtok(buf,subsep);
         tmp.sServername=strtok(NULL,subsep);
         tmp.iPort=atoi(strtok(NULL,subsep));
         if((subtoken=strtok(NULL,subsep))!=NULL){
             tmp.sUser=subtoken;
             if((subtoken=strtok(NULL,subsep))!=NULL){
               	tmp.sPasswd=subtoken;
             }else{
               	tmp.sPasswd="a";
                }
           } 
         else{
               tmp.sUser="a";
               tmp.sPasswd="a";
           }
         servers.push_back(tmp);
         i++;
	 }
	 file.close();
	 return i;
}
////////////////////////////////////
/// <------  protected funtions

////////////////////////////////////
/// ------>  private funtions
bool Dispatcher::loadenvironment() throw (const string &){
       try{
             char *typechars= getenv("FLEATYPE");
             if(typechars==NULL)
                 sfleatype = "Normal";
             else
                 sfleatype=typechars;
             
        }
       catch(const char *e){
             throw string(e);
       }

}


bool Dispatcher::initlibc() throw (const string &)
{

      if(!plibc){
           if(!(plibc = dlopen ("libc.so", RTLD_LAZY))){
                if(!(plibc = dlopen ("libc.so.6", RTLD_LAZY))){
                      if(!(plibc = dlopen ("libc.so.5", RTLD_LAZY))){
                                    throw string("Error ocurs while loading libc");
                             }
                }
           }
      }
      try{
            oldconnect=(old_connect)getorignalfunc("connect");
            oldsend=(old_send)getorignalfunc("send");
            oldrecv=(old_recv)getorignalfunc("recv");
            oldsendto=(old_sendto)getorignalfunc("sendto");
            oldrecvfrom=(old_recvfrom)getorignalfunc("recvfrom");
            oldbind=(old_bind)getorignalfunc("bind");

      }
      catch(const string &s){
            throw s;
      }
      return true;

}

void * Dispatcher::getorignalfunc(const char * name) const throw (const string &){
      void * out;
      out = dlsym(plibc, name);
      if(dlerror()!=NULL){
           throw (string("error ocured while loading the following orignal function from libc:")+string(name));
      }
      return out;
}

/// <------  private funtions
/////////////////////////////////////

